package cn.net.autocode.core.utils;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class TreeUtils {
	/**
	 * 将菜单转化为树形结构
     */
	public static JSONArray commonTree(JSONArray arrays){
		JSONArray trees = new JSONArray();
		int lens = arrays.size();
		for(int i=0;i<lens;i++){
			JSONObject item = arrays.getJSONObject(i);
			if(item.getString("parentId")==null||item.getString("parentId").isBlank()||"-1".equals(item.getString("parentId"))||"0".equals(item.getString("parentId"))){
				JSONArray child = TreeUtils.children(arrays, item.getString("id"));
				if(!child.isEmpty()){
					item.put("children", child);
				}
				trees.add(item);
			}
		}
		return trees;
	}
	
	private static JSONArray children(JSONArray sources,String parentId){
		JSONArray childs = new JSONArray();
		int lens = sources.size();
		for(int i=0;i<lens;i++){
			JSONObject item = sources.getJSONObject(i);
            String itemParentId = item.getString("parentId");
			if(parentId==null || parentId.isBlank()){
                if(itemParentId==null || itemParentId.isBlank()){
                    childs.add(item);
                }
			}else if(parentId.equals(itemParentId)){
                childs.add(item);
            }
		}
		
		for(int j=0;j<childs.size();j++){
			JSONObject subitem = childs.getJSONObject(j);
			JSONArray subChild = TreeUtils.children(sources, subitem.getString("id"));
			if(!subChild.isEmpty()){
				subitem.put("children", subChild);
			}
		}
		return childs;
	}
}
